{% extends "base.html" %}

{% block title %}首页 - 微信公众号文章采集系统{% endblock %}

{% block content %}
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">配置信息</h5>
                    <button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#cleanDatabaseModal">
                        清理数据库
                    </button>
                </div>
                <div class="card-body">
                    <form id="collect-form">
                        <div class="mb-3">
                            <label for="token" class="form-label">Token</label>
                            <input type="text" class="form-control" id="token" name="token" required>
                        </div>
                        <div class="mb-3">
                            <label for="cookie" class="form-label">Cookie</label>
                            <input type="text" class="form-control" id="cookie" name="cookie" required>
                        </div>
                        <div class="mb-3">
                            <label for="fakeid" class="form-label">Fakeid</label>
                            <input type="text" class="form-control" id="fakeid" name="fakeid" required>
                        </div>
                        <div class="mb-3">
                            <button type="submit" class="btn btn-primary">开始采集</button>
                            <button type="button" class="btn btn-success" id="save-config">保存配置</button>
                            <button type="button" class="btn btn-danger" id="clear-config">清除配置</button>
                            <a href="/articles/preview" class="btn btn-info" target="_blank">文章预览</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 清理数据库模态框 -->
    <div class="modal fade" id="cleanDatabaseModal" tabindex="-1" aria-labelledby="cleanDatabaseModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="cleanDatabaseModalLabel">清理数据库</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="clean-database-form">
                        <div class="mb-3">
                            <label for="clean-days" class="form-label">清理多少天前的数据</label>
                            <input type="number" class="form-control" id="clean-days" name="days" value="7" min="1">
                            <div class="form-text">将删除指定天数之前的所有文章、PDF和HTML文件</div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirm-clean">确认清理</button>
                </div>
            </div>
        </div>
    </div>


    <!-- 文章列表 -->
    <div class="row mt-4">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">文章列表</h5>
                </div>
                <div class="card-body">
                    <div id="message-container"></div>
                    <div class="loading"></div>
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th style="width: 20%">标题</th>
                                    <th style="width: 10%">作者</th>
                                    <th style="width: 15%">发布时间</th>
                                    <th style="width: 45%">内容预览</th>
                                    <th style="width: 10%">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for article in articles %}
                                <tr>
                                    <td>{{ article.title }}</td>
                                    <td>{{ article.author }}</td>
                                    <td>{{ article.create_time }}</td>
                                    <td>
                                        <div class="content-preview">
                                            {{ article.content_preview|safe }}
                                        </div>
                                    </td>
                                    <td>
                                        <div class="btn-group">
                                            <a href="/preview/{{ article.id }}" class="btn btn-sm btn-info" target="_blank">
                                                <i class="fas fa-eye"></i> 预览
                                            </a>
                                            {% if article.pdf_path %}
                                            <a href="/download/{{ article.pdf_path }}" class="btn btn-sm btn-success">
                                                <i class="fas fa-download"></i> 下载PDF
                                            </a>
                                            {% else %}
                                            <button type="button" class="btn btn-sm btn-primary generate-pdf" onclick="generatePDF({{ article.id }})">
                                                <i class="fas fa-file-pdf"></i> 生成PDF
                                            </button>
                                            {% endif %}
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    {% if total_pages > 1 %}
                    <nav aria-label="Page navigation">
                        <ul class="pagination">
                            {% for page in range(1, total_pages + 1) %}
                            <li class="page-item {% if page == current_page %}active{% endif %}">
                                <a class="page-link" href="?page={{ page }}">{{ page }}</a>
                            </li>
                            {% endfor %}
                        </ul>
                    </nav>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 文章内容模态框 -->
<div class="modal fade" id="contentModal" tabindex="-1" aria-labelledby="contentModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="contentModalLabel">文章内容</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="articleContent"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<style>
.content-preview {
    max-height: 100px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    font-size: 14px;
    color: #666;
    line-height: 1.5;
}

.content-preview img {
    max-width: 100%;
    height: auto;
}

.table td {
    vertical-align: middle;
}

.table th {
    background-color: #f8f9fa;
    font-weight: 600;
}

.modal-lg {
    max-width: 90%;
}
.modal-body {
    padding: 20px;
}
#articleContent {
    font-size: 16px;
    line-height: 1.8;
}
#articleContent img {
    max-width: 100%;
    height: auto;
    margin: 10px 0;
}
.btn-group {
    display: flex;
    gap: 5px;
}
</style>
{% endblock %}

{% block extra_js %}
<script>
// 显示消息提示
function showMessage(message, type = 'info') {
    const alertHtml = `
        <div class="alert alert-${type} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;
    $('#message-container').html(alertHtml);
}

// 显示加载动画
function showLoading(message = '处理中...') {
    $('.loading').html(`
        <div class="d-flex justify-content-center">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">${message}</span>
            </div>
        </div>
    `).show();
}

// 隐藏加载动画
function hideLoading() {
    $('.loading').hide();
}

// 配置管理函数
const ConfigManager = {
    // 加载配置
    loadConfig: function() {
        try {
            const configStr = localStorage.getItem('wechatConfig');
            if (configStr) {
                const config = JSON.parse(configStr);
                if (config.token) $('#token').val(config.token);
                if (config.cookie) $('#cookie').val(config.cookie);
                if (config.fakeid) $('#fakeid').val(config.fakeid);
                console.log('配置加载成功');
            }
        } catch (error) {
            console.error('加载配置失败:', error);
            showMessage('加载配置失败: ' + error.message, 'danger');
        }
    },

    // 保存配置
    saveConfig: function() {
        try {
            const config = {
                token: $('#token').val().trim(),
                cookie: $('#cookie').val().trim(),
                fakeid: $('#fakeid').val().trim()
            };

            if (!config.token || !config.cookie || !config.fakeid) {
                showMessage('请填写完整的配置信息', 'warning');
                return;
            }

            localStorage.setItem('wechatConfig', JSON.stringify(config));
            showMessage('配置已保存', 'success');
        } catch (error) {
            console.error('保存配置失败:', error);
            showMessage('保存配置失败: ' + error.message, 'danger');
        }
    },

    // 清除配置
    clearConfig: function() {
        try {
            localStorage.removeItem('wechatConfig');
            $('#token').val('');
            $('#cookie').val('');
            $('#fakeid').val('');
            showMessage('配置已清除', 'success');
        } catch (error) {
            console.error('清除配置失败:', error);
            showMessage('清除配置失败: ' + error.message, 'danger');
        }
    }
};

// 加载文章URL列表
function loadArticleUrls() {
    showLoading('正在加载文章列表...');
    
    $.ajax({
        url: '/api/articles/urls',
        method: 'GET',
        success: function(response) {
            if (response.code === 0) {
                const select = $('#url-select');
                select.empty().append('<option value="">请选择文章...</option>');
                
                response.data.forEach(article => {
                    select.append(`<option value="${article.url}">${article.title}</option>`);
                });
                
                showMessage('文章列表加载成功', 'success');
            } else {
                showMessage(response.message || '加载文章列表失败', 'danger');
            }
        },
        error: function(xhr) {
            showMessage(xhr.responseJSON?.message || '服务器错误', 'danger');
        },
        complete: function() {
            hideLoading();
        }
    });
}

// 生成PDF函数
function generatePDF(articleId) {
    console.log('开始生成PDF，文章ID:', articleId);
    const btn = $(`.generate-pdf[onclick*="${articleId}"]`);
    console.log('找到按钮:', btn.length > 0);
    
    if (btn.length === 0) {
        console.error('未找到对应的按钮');
        return;
    }
    
    btn.prop('disabled', true);
    btn.html('<i class="fas fa-spinner fa-spin"></i> 生成中...');
    
    $.ajax({
        url: `/api/generate-pdf/${articleId}`,
        method: 'POST',
        success: function(response) {
            console.log('PDF生成响应:', response);
            if (response.code === 0) {
                showMessage('PDF生成成功！', 'success');
                setTimeout(() => window.location.reload(), 1500);
            } else {
                showMessage(response.message || '生成PDF失败', 'danger');
                btn.prop('disabled', false);
                btn.html('<i class="fas fa-file-pdf"></i> 生成PDF');
            }
        },
        error: function(xhr, status, error) {
            console.error('PDF生成错误:', {xhr, status, error});
            showMessage(xhr.responseJSON?.message || '服务器错误', 'danger');
            btn.prop('disabled', false);
            btn.html('<i class="fas fa-file-pdf"></i> 生成PDF');
        }
    });
}

// 页面加载完成后执行
$(document).ready(function() {
    console.log('页面加载完成');
    
    // 加载配置
    ConfigManager.loadConfig();

    // 绑定保存配置按钮事件
    $('#save-config').click(function() {
        ConfigManager.saveConfig();
    });

    // 绑定清除配置按钮事件
    $('#clear-config').click(function() {
        ConfigManager.clearConfig();
    });

    // 绑定采集文章表单提交事件
    $('#collect-form').submit(function(e) {
        e.preventDefault();
        showLoading();

        const formData = {
            token: $('#token').val(),
            cookie: $('#cookie').val(),
            fakeid: $('#fakeid').val()
        };

        $.ajax({
            url: '/api/articles/collect',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(response) {
                if (response.code === 0) {
                    showMessage('文章采集成功', 'success');
                    setTimeout(() => window.location.reload(), 1500);
                } else {
                    showMessage(response.message || '文章采集失败', 'danger');
                }
            },
            error: function(xhr) {
                showMessage(xhr.responseJSON?.message || '服务器错误', 'danger');
            },
            complete: function() {
                hideLoading();
            }
        });
    });

    // 绑定清理数据库确认按钮事件
    $('#confirm-clean').click(function() {
        if (!confirm('确定要清理数据库吗？此操作不可恢复！')) {
            return;
        }

        showLoading('正在清理数据库...');
        
        const days = parseInt($('#clean-days').val());
        
        $.ajax({
            url: '/api/database/clean',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ days: days }),
            success: function(response) {
                if (response.code === 0) {
                    showMessage(`成功清理 ${response.data.deleted_count} 条记录`, 'success');
                    $('#cleanDatabaseModal').modal('hide');
                    setTimeout(() => window.location.reload(), 1500);
                } else {
                    showMessage(response.message || '清理失败', 'danger');
                }
            },
            error: function(xhr) {
                showMessage(xhr.responseJSON?.message || '服务器错误', 'danger');
            },
            complete: function() {
                hideLoading();
            }
        });
    });

    // 加载文章URL列表
    loadArticleUrls();

    // 绑定URL选择事件
    $('#url-select').change(function() {
        const selectedUrl = $(this).val();
        if (selectedUrl) {
            $('#url').val(selectedUrl);
        }
    });

    // 查看文章内容
    $('.view-content').click(function() {
        const articleId = $(this).data('article-id');
        showLoading('正在加载文章内容...');
        
        $.ajax({
            url: `/api/articles/${articleId}/content`,
            method: 'GET',
            success: function(response) {
                if (response.code === 0) {
                    $('#articleContent').html(response.data.content);
                } else {
                    showMessage(response.message || '获取文章内容失败', 'danger');
                }
            },
            error: function(xhr) {
                showMessage(xhr.responseJSON?.message || '服务器错误', 'danger');
            },
            complete: function() {
                hideLoading();
            }
        });
    });
});
</script>
{% endblock %} 